// components/profile/learning-chart/learning-chart.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      type: String,
      value: '学习趋势'
    },
    chartPeriod: {
      type: String,
      value: 'week',
      observer: 'onPeriodChange'
    },
    timelineData: {
      type: Array,
      value: [],
      observer: 'onDataChange'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {},

  /**
   * 组件生命周期函数，在组件实例进入页面节点树时执行
   */
  attached() {
    this.initLearningChart();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 初始化学习趋势图表
     */
    initLearningChart() {
      try {
        // 获取canvas上下文
        const ctx = wx.createCanvasContext('learningChart', this);
        const { timelineData, chartPeriod } = this.data;

        // 根据图表周期过滤数据
        let chartData = [];
        if (chartPeriod === 'week') {
          chartData = this.getRecentDaysData(timelineData, 7);
        } else {
          chartData = this.getRecentDaysData(timelineData, 30);
        }

        // 如果没有数据，显示空状态
        if (chartData.length === 0) {
          this.drawEmptyChart(ctx);
          return;
        }

        // 绘制图表
        this.drawChart(ctx, chartData);
      } catch (error) {
        console.error('初始化图表失败:', error);
      }
    },

    /**
     * 获取最近N天的数据
     */
    getRecentDaysData(timelineData, days) {
      const result = [];
      const now = new Date();

      // 创建日期映射
      const dateMap = {};
      timelineData.forEach(item => {
        dateMap[item.date] = item;
      });

      // 生成最近N天的日期
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        const dateStr = this.formatDate(date);

        // 如果当天有数据，使用实际数据；否则使用默认值
        const dayData = dateMap[dateStr] || {
          date: dateStr,
          wordsLearned: 0,
          reviewedWords: 0,
          studyTime: 0
        };

        result.push(dayData);
      }

      return result;
    },

    /**
     * 绘制图表
     */
    drawChart(ctx, chartData) {
      const canvasWidth = 300; // 简化处理，实际应该获取canvas实际宽度
      const canvasHeight = 200;
      const margin = { top: 20, right: 20, bottom: 40, left: 40 };

      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);

      // 计算绘制区域
      const drawWidth = canvasWidth - margin.left - margin.right;
      const drawHeight = canvasHeight - margin.top - margin.bottom;

      // 找到最大值用于缩放
      const maxValue = Math.max(
        ...chartData.map(item => item.wordsLearned + item.reviewedWords),
        10 // 确保至少有一个合理的最大值
      );

      // 绘制坐标轴
      ctx.beginPath();
      ctx.strokeStyle = '#ddd';
      ctx.lineWidth = 1;

      // X轴
      ctx.moveTo(margin.left, canvasHeight - margin.bottom);
      ctx.lineTo(canvasWidth - margin.right, canvasHeight - margin.bottom);

      // Y轴
      ctx.moveTo(margin.left, margin.top);
      ctx.lineTo(margin.left, canvasHeight - margin.bottom);
      ctx.stroke();

      // 绘制柱状图
      const barWidth = drawWidth / (chartData.length * 2 + 1);
      const gap = barWidth / 2;

      chartData.forEach((item, index) => {
        const x = margin.left + index * barWidth * 2 + gap;

        // 新学单词柱形
        const learnedHeight = (item.wordsLearned / maxValue) * drawHeight;
        ctx.fillStyle = '#845EC2';
        ctx.fillRect(x, canvasHeight - margin.bottom - learnedHeight, barWidth, learnedHeight);

        // 复习单词柱形
        const reviewedHeight = (item.reviewedWords / maxValue) * drawHeight;
        ctx.fillStyle = '#FF6B6B';
        ctx.fillRect(x + barWidth + gap, canvasHeight - margin.bottom - reviewedHeight, barWidth, reviewedHeight);

        // 绘制日期标签
        ctx.fillStyle = '#666';
        ctx.font = '10px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText(item.date.split('-').slice(1).join('/'), x + barWidth + gap, canvasHeight - margin.bottom + 15);
      });

      // 绘制图例
      ctx.font = '12px sans-serif';
      ctx.textAlign = 'left';

      // 新学单词图例
      ctx.fillStyle = '#845EC2';
      ctx.fillRect(margin.left, margin.top - 15, 12, 6);
      ctx.fillStyle = '#666';
      ctx.fillText('新学', margin.left + 20, margin.top - 10);

      // 复习单词图例
      ctx.fillStyle = '#FF6B6B';
      ctx.fillRect(margin.left + 80, margin.top - 15, 12, 6);
      ctx.fillStyle = '#666';
      ctx.fillText('复习', margin.left + 100, margin.top - 10);

      // 绘制图表
      ctx.draw();
    },

    /**
     * 绘制空图表
     */
    drawEmptyChart(ctx) {
      const canvasWidth = 300;
      const canvasHeight = 200;

      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);

      // 绘制背景图案
      ctx.beginPath();
      ctx.fillStyle = '#f8f8f8';
      ctx.arc(canvasWidth / 2, canvasHeight / 2 - 20, 40, 0, 2 * Math.PI);
      ctx.fill();

      // 绘制书本图标
      ctx.fillStyle = '#e0e0e0';
      // 书本轮廓
      ctx.fillRect(canvasWidth / 2 - 20, canvasHeight / 2 - 30, 40, 40);
      // 书本装饰
      ctx.fillStyle = '#d0d0d0';
      ctx.fillRect(canvasWidth / 2 - 20, canvasHeight / 2 - 30, 8, 40);
      ctx.fillRect(canvasWidth / 2 - 20, canvasHeight / 2 - 5, 40, 2);

      // 绘制主要提示文本
      ctx.fillStyle = '#666';
      ctx.font = 'bold 16px sans-serif';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('暂无学习数据', canvasWidth / 2, canvasHeight / 2 + 25);

      // 绘制引导文本
      ctx.fillStyle = '#999';
      ctx.font = '12px sans-serif';
      ctx.fillText('开始你的学习之旅吧！', canvasWidth / 2, canvasHeight / 2 + 45);

      // 绘制图表
      ctx.draw();
    },

    /**
     * 格式化日期
     */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    /**
     * 切换图表周期
     */
    onPeriodChange(newVal) {
      if (newVal) {
        this.setData({ chartPeriod: newVal });
        this.initLearningChart();
        // 触发父组件事件
        this.triggerEvent('periodchange', { period: newVal });
      }
    },

    /**
     * 数据变化时重新绘制图表
     */
    onDataChange() {
      this.initLearningChart();
    }
  }
})